package com.gsi.multichannel.sf.pipelet.storelocator;

import java.net.MalformedURLException;
import java.net.URL;

import com.intershop.beehive.configuration.capi.common.Configuration;
import com.intershop.beehive.core.capi.configuration.ConfigurationMgr;
import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.beehive.core.capi.request.Request;

/**
 * Returns a store map url based on the customer information
 */
public class GetStoreMapUrl extends Pipelet
{
    private static final String SIMPLE_MAP_BASE_URL = "SIMPLE_MAP_BASE_URL";
    private static final String ADV_MAP_BASE_URL = "ADV_MAP_BASE_URL";
    private static final String ADV_MAP_DYNAMIC_SUFFIX = "ADV_MAP_DYNAMIC_SUFFIX";
    private static final String ADV_MAP_STATIC_SUFFIX = "ADV_MAP_STATIC_SUFFIX";
    private static final String MAP_USE_SIMPLE = "SIMPLE";
    private static final String MAP_USE_ADVANCED = "ADVANCED";
    
    /**
     * Constant used to access the pipeline dictionary with key 'storeMapUrl'
     * 
     * The url
     */
    public static final String DN_STORE_MAP_URL = "storeMapUrl";
    /**
     * Constant used to access the pipeline dictionary with key 'mapUse'
     * 
     * The mapping engine to use
     */
    public static final String DN_MAP_USE = "MapUse";
    /**
     * Constant used to access the pipeline dictionary with key 'CurrentRequest'
     */
    public static final String DN_CURRENT_REQUEST = "CurrentRequest";
    /**
     * Constant used to access the pipeline dictionary with key 'storeMapStaticUrl'
     * 
     * Static base url for the google mapping functionality
     */
    public static final String DN_STORE_MAP_STATIC_URL = "storeMapStaticUrl";

    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as a
     * parameter.
     * 
     * @param dict
     *            The pipeline dictionary to be used.
     * @throws PipeletExecutionException
     *             Thrown in case of severe errors that make the pipelet execute
     *             impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict)
    throws PipeletExecutionException {        
        // lookup 'MapUse' in pipeline dictionary
        String mapUse = (String)dict.get(DN_MAP_USE);
        if (null == mapUse)
        {
            throw new PipeletExecutionException("Mandatory input parameter 'MapUse' not available in pipeline dictionary.");
        }
        
        // lookup 'CurrentRequest' in pipeline dictionary
        Request currentRequest = (Request)dict.get(DN_CURRENT_REQUEST);

        Configuration config = ConfigurationMgr.getInstance().getConfiguration();
        URL baseURL = null;
        URL staticURL = null;
        
        boolean isAdvancedURLException = false;
        boolean isSimpleURLException = false;
        
        //These are defaults if the currentRequest is null
        String languageCode = "en";
        String regionCode = "US";
        
        if (currentRequest != null) {
            languageCode = currentRequest.getLocale().getLanguage();
            regionCode = currentRequest.getLocale().getCountry();
        }
        
        if (MAP_USE_ADVANCED.equalsIgnoreCase(mapUse)) {
            try {
                String baseAdvUrlStr = config.getString(ADV_MAP_BASE_URL);
                String dynamicUrlSuffix = config.getString(ADV_MAP_DYNAMIC_SUFFIX);
                String staticUrlSuffix = config.getString(ADV_MAP_STATIC_SUFFIX);
                baseURL = new URL(baseAdvUrlStr + dynamicUrlSuffix);
                baseURL = buildURL(baseURL, "language=" + languageCode);
                baseURL = buildURL(baseURL, "region=" + regionCode);
                staticURL = new URL(baseAdvUrlStr + staticUrlSuffix);
            } catch (MalformedURLException e) {
                isAdvancedURLException = true;
            }
        } else if (MAP_USE_SIMPLE.equalsIgnoreCase(mapUse)) {
           try {
               baseURL = new URL(config.getString(SIMPLE_MAP_BASE_URL));
           } catch (MalformedURLException e) {
               isSimpleURLException = true;
           } 
        }
        
        if (isAdvancedURLException && mapUse.equalsIgnoreCase(MAP_USE_ADVANCED)) {
            return PIPELET_ERROR;
        }
        
        if (isSimpleURLException && mapUse.equalsIgnoreCase(MAP_USE_SIMPLE)) {
            return PIPELET_ERROR;
        }
        
        dict.put(DN_STORE_MAP_URL, baseURL);
        dict.put(DN_STORE_MAP_STATIC_URL, staticURL);
        return PIPELET_NEXT;
    }
    
    private URL buildURL(URL url, String parameter) 
    throws MalformedURLException {
        String urlString = url.toString();
        if (urlString.contains("&")) {
            urlString += "&" + parameter;
        } else if (urlString.contains("?")) {
            urlString += "&" + parameter;
        } else {
            urlString += "?" + parameter;
        }
        
        return new URL(urlString);
    }
}